package com.bw.gmall.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class DwdBaseLog extends BaseApp {
    public static void main(String[] args) {
        new DwdBaseLog().start(Constant.TOPIC_LOG,Constant.TOPIC_DWD_BASE_LOG,4,10011);

    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {

        //1。etl清洗数据
        SingleOutputStreamOperator<JSONObject> etlstream = etl(dataStreamSource);
        etlstream.print();


        // 2.添加水位线并keyby
        KeyedStream<JSONObject, String> keyBy = keyby1(etlstream);

        // 3.新来用户校验
        SingleOutputStreamOperator<JSONObject> newstream = is_newstream(keyBy);

//        newstream.print("1");

        // 4.分流
        OutputTag<String> startTag = new OutputTag<String>("start", TypeInformation.of(String.class));
        OutputTag<String> errTag = new OutputTag<String>("err",TypeInformation.of(String.class));
        OutputTag<String> displayTag = new OutputTag<String>("display", TypeInformation.of(String.class));
        OutputTag<String> actionTag = new OutputTag<String>("action", TypeInformation.of(String.class));

        SingleOutputStreamOperator<String> splitStream = splitStream(newstream, startTag, errTag, displayTag, actionTag);
//        splitStream.print("22");

        // 5.写入到kafka

        SideOutputDataStream<String> startstream = splitStream.getSideOutput(startTag);
        SideOutputDataStream<String> errstream = splitStream.getSideOutput(errTag);
        SideOutputDataStream<String> displaystream = splitStream.getSideOutput(displayTag);
        SideOutputDataStream<String> actiontream = splitStream.getSideOutput(actionTag);

        //写入
        startstream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        errstream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        displaystream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        actiontream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));

//        splitStream.print();

        splitStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));

//        System.out.println(111);

    }

    //4.分流
    private static SingleOutputStreamOperator<String> splitStream(SingleOutputStreamOperator<JSONObject> newstream, OutputTag<String> startTag, OutputTag<String> errTag, OutputTag<String> displayTag, OutputTag<String> actionTag) {
        return newstream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject jsonObject, ProcessFunction<JSONObject, String>.Context context, Collector<String> collector) throws Exception {

                JSONObject err = jsonObject.getJSONObject("err");

                if (err != null) {
                    context.output(errTag, jsonObject.toJSONString());
                    jsonObject.remove("err");
                }

                JSONObject start = jsonObject.getJSONObject("start");
                JSONObject page = jsonObject.getJSONObject("page");
                JSONObject common = jsonObject.getJSONObject("common");
                Long ts = jsonObject.getLong("ts");

                if (start != null) {
                    context.output(startTag, jsonObject.toJSONString());
                    jsonObject.remove("start");
                } else if (page != null) {
                    //displays
                    JSONArray displays = jsonObject.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.put("page", page);
                            display.put("common", common);
                            display.put("ts", ts);
                            context.output(displayTag, display.toJSONString());
                        }
                        jsonObject.remove("displays");
                    }

                    //actions
                    JSONArray actions = jsonObject.getJSONArray("actions");

                    if (actions != null) {

                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);

                            action.put("page", page);
                            action.put("common", common);
                            action.put("ts", ts);

                            context.output(actionTag, action.toJSONString());
                        }
                        jsonObject.remove("actions");
                    }
                    collector.collect(jsonObject.toJSONString());
                }
            }
        });
    }

    private static SingleOutputStreamOperator<JSONObject> is_newstream(KeyedStream<JSONObject, String> keyBy) {
        return keyBy.map(new RichMapFunction<JSONObject, JSONObject>() {
            ValueState<String> state;

            @Override
            public void open(Configuration parameters) {
                state = getRuntimeContext().getState(new ValueStateDescriptor<>("state", Types.STRING));
            }

            @Override
            public JSONObject map(JSONObject jsonObject) throws Exception {
                String is_new = jsonObject.getJSONObject("common").getString("is_new");
                Long ts = jsonObject.getLong("ts");

                String tsToDate = DateFormatUtil.tsToDate(ts);
                String value = state.value();
                if ("1".equals(is_new)) {

                    if (value != null && !value.equals(tsToDate)) {
                        jsonObject.getJSONObject("common").put("is_new", 0);
                    } else {
                        state.update(tsToDate);
                    }
                }
                return jsonObject;
            }
        });
    }

    //2.新老用户校验
    private static  KeyedStream<JSONObject, String> keyby1(SingleOutputStreamOperator<JSONObject> etl) {
        return etl.assignTimestampsAndWatermarks(WatermarkStrategy
                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                .withTimestampAssigner((event, timestamp) -> event.getLong("ts"))).keyBy(x -> x.getJSONObject("common").getString("mid"));
    }

    //1.ELT清洗数据
    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
         return stream.flatMap(new RichFlatMapFunction<String, JSONObject>() {

            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                if (s != null) {
                    JSONObject jsonObject = JSON.parseObject(s);
                    Long ts = jsonObject.getLong("ts");


                    JSONObject common = jsonObject.getJSONObject("common");

                    if (common != null && ts != null) {
                        String mid = common.getString("mid");

                        if (mid != null && !"".equals(mid)) {
                            collector.collect(jsonObject);
                        }
                    }
                }
            }
        });
    }


}
